/**
 * 
 */
package spitfire.ksim.network;

import spitfire.ksim.network.KNetAddress;
import spitfire.ksim.network.KNetwork;
import spitfire.ksim.network.KNetworkModule;
import spitfire.ksim.network.KPacket;
import spitfire.ksim.util.TPoint;

/**
 * <p>
 * A wireless network module implementation for {@link KNetworkModule}.
 * Wireless network module has a radio range limitation. A wireless module is 
 * considered adjacent with another when their distance is less than its radio
 * range.
 * </p>
 * 
 * @author Adam
 *
 */
public abstract class KWirelessNetworkModule implements KNetworkModule {

	private KNetAddress netAddr;
	private KNetwork network;
	private double radioRange;
	
	public abstract TPoint getLocation();
	
	public KWirelessNetworkModule(KNetwork network, double radioRange) {
		this.radioRange = radioRange;
		connectNetwork(network);
	}

	/**
	 * @param network
	 */
	@Override
	public void connectNetwork(KNetwork network) {
		if (network == null) {
			throw new NullPointerException("Network cannot be null");
		}
		if (this.network != null) {
			disconnectNetwork();
		}
		this.network = network; 
		netAddr = network.register(this);
	}

	@Override
	public void disconnectNetwork() {
		network.deregister(this);
		network = null;
		netAddr = null;
	}
	
	@Override
	public void setNetAddr(KNetAddress netAddr) {
		this.netAddr = netAddr;
	}

	@Override
	public KNetAddress getNetAddr() {
		return netAddr;
	}

	@Override
	public KNetwork getNetwork() {
		return network;
	}

	@Override
	public void send(KNetAddress destination, Object payload) {
		network.transmit(new KPacket(getNetAddr(), destination, payload));
	}
	
	@Override
	public boolean adjacentWith(KNetworkModule netModule) {
		if (netModule instanceof KWirelessNetworkModule) {
			KWirelessNetworkModule module = (KWirelessNetworkModule)netModule;
			return (TPoint.dist(getLocation(), module.getLocation()) < radioRange); 
		} else {
			return false; 
		}
	}
}
